/* 
 
 RC Transmitter reference code
 
 */

#include "config.h"
#include <SPI.h>
#include <RF22.h>

#define CHANNELS 8
#define FREQUENCY 458.5  //Change to whatever you want, remember to change rx as well!


#define tonePin 5
#define greenLED 18
#define redLED 19

#define details(name) (uint8_t*)&name,sizeof(name)

struct SEND_DATA_STRUCTURE{
  short AxisOut[CHANNELS];
};

struct TELE_DATA_STRUCTURE{
  byte RSSI;
  byte RxBad;
  float Alt;
};

short AxisOld[CHANNELS];

SEND_DATA_STRUCTURE txdata;
TELE_DATA_STRUCTURE teledata;

// Singleton instance of the radio
RF22 rf22;

static uint32_t currentTime = 0;
volatile byte channel_no=0;
volatile byte transmitted=1;
volatile byte channel_count=0;
volatile unsigned int time_temp;
byte GPIO2;
byte rssi;

void setup() 
{
  //analogWrite(tonePin,128);
  //Serial.begin(9600);
  //Serial.println("Started");
  tone(tonePin, 262, 50);

  RF22Initialization();
  PPMInitialization();
  
  #if defined(TELEMETRY_FRSKY)    
    configure_FrSky();
  #endif
}

void loop()
{
  currentTime = micros();
  
  if ((transmitted==0) && (channel_count>3) && (channel_count<13)) {
    inputFilter();
    GPIO2SwitchCheck();

    rf22.send(details(txdata));
    rf22.waitPacketSent();
    digitalWrite(greenLED, HIGH);
    transmitted = 1;
    
  } else if (rf22.recv((uint8_t*)&teledata,(uint8_t*)sizeof(teledata))) {
      
      digitalWrite(greenLED, LOW);
      digitalWrite(tonePin, LOW);
      
      rssi = rf22.lastRssi();      
      
      if (teledata.RxBad != 0)
      {
        //4000Hz tone for bad packets
        tone(tonePin, 4000, 5);
      }
      else if (teledata.RSSI < 85)
      {
        //2000Hz tone for RSSI warning
        tone(tonePin, 2000, 5);
      }
      /*    
      Serial.print(teledata.RSSI,DEC);
      Serial.print(", ");
      Serial.print(teledata.RxBad,DEC);
      Serial.print(", ");
      Serial.print(teledata.Alt,DEC);
      Serial.print(", ");
      Serial.println(rssi);
      */
      
      #if defined(TELEMETRY_FRSKY)    
        telemetry_frsky();
      #endif
  }
}












